<template>
	<div style="padding:0 37px 0 44px">
		<div class="breadcrumb-father">
			<div class="new-breadcrumb">
				
				<router-link  :to="{path:'/welcome'}">
					<img src="../../assets/imgs/Home.png" alt="">
				</router-link>
				<!-- <a href="javascript:void(0)">
				</a> -->
				<span>{{$t('index.Device')}}</span>
				<span class="arrow">></span>
				<!-- <a href="javascript:void(0)">
				</a> -->
				<span>{{$t('index.Device')}}</span>
			</div>
		</div>

		<div class="card-table">
			<div class="card-table-title">
				<svg aria-hidden="true" class="svg-icon svg-title-icon">
					<use xlink:href="#icon-shebeiguanli"></use>
				</svg>
				<span>{{ $t('index.Device') }}</span>	
			</div>
			<!--搜索输入框-->
			<div class="search">
				<div class="search-input">
					<div class="date-wrapper">
						<label>{{ $t('inputBox.deploymentDate') }}</label>
						<div class="date-line"></div>
						<el-date-picker v-model="searchDeviceData.startDate" value-format="yyyy-MM-dd" @keyup.enter.native="handleFilter(0)" clearable :editable=false type="date"></el-date-picker>
					</div>
					<div>
						<label>{{ $t('inputBox.endDateOfBinding') }}</label>
						<el-date-picker v-model="searchDeviceData.endDate" value-format="yyyy-MM-dd" @keyup.enter.native="handleFilter(0)" clearable :editable=false type="date"></el-date-picker>
					</div>
					<div>
						<label>{{ $t('trade.DeviceID') }}</label>
						<el-input v-model="searchDeviceData.termId" clearable :maxlength=16 @keyup.enter.native="handleFilter(0)"></el-input>
					</div>
					<div>
						<label>{{ $t('inputBox.deviceType') }}</label>
						<el-select v-model="searchDeviceData.payType" popper-class="el-select-custom" @keyup.enter.native="handleFilter(0)" clearable :placeholder="$t('placeH.All')">
							<el-option :label="$t('inputBox.QRcode')" value="0"> </el-option>
							<el-option :label="$t('inputBox.scanner')" value="1"> </el-option>
						</el-select>
					</div>
					<div>
						<label>{{ $t('inputBox.deviceStatus') }}</label>
						<el-select v-model="searchDeviceData.state" popper-class="el-select-custom" @keyup.enter.native="handleFilter(0)" clearable :placeholder="$t('placeH.All')">
							<el-option :label="$t('inputBox.disabled')" value="0"> </el-option>
							<el-option :label="$t('inputBox.enabled')" value="1"> </el-option>
						</el-select>
					</div>
					<div>
						<label>{{ $t('inputBox.merchant') }}</label>
						<el-select v-model="merData" popper-class="el-select-custom" clearable filterable remote :remote-method="remoteMethod" @keyup.enter.native="handleFilter(0)" placeholder="" @change='selectMer()' value-key="merchantId" @clear='clearMer()'>
							<el-option v-for="item in queryMerData" :key="item.merchantId" :label="item.merchantName" :value="item">
							</el-option>
						</el-select>
					</div>
					<div>
						<label>{{ $t('inputBox.shop') }}</label>
						<el-select v-model="searchDeviceData.shopName" popper-class="el-select-custom" @keyup.enter.native="handleFilter(0)" clearable filterable :placeholder="select_shop==true?$t('placeH.All'):$t('inputBox.pleaseChooseMerchant')" :disabled='showQueryShop'>
							<el-option v-for="item in queryShopData" :key="item.shopId" :label="item.shopName" :value="item.shopName">
							</el-option>
						</el-select>
					</div>
					
					<div class="search-btn-group">
						<el-button class="blue-btn mini2-btn" @click="handleFilter(0)">{{$t('button.search')}}</el-button>
						<el-button class='blue-btn mini2-btn' @click='delSelect()'>{{$t('button.Reset')}}</el-button>
					</div>
				</div>
			</div>
			
			<div class="table-border">
				<div class="search-result-head">
					<span>{{ searchInfo }}</span>
					<span style="float:right;">
						<a href="javascript:void(0)" @click="export2Excel()" :title="$t('button.SaveResult')"><icon-svg icon-class="daochu"></icon-svg></a> 
						<a href="javascript:void(0)" v-if=" userPhone !== '13501189583' && userPhone !== '15018955912' && userPhone !== '15219441946' " @click="dialogDeviceAdd = true" :title="$t('button.New')"><icon-svg icon-class="jia"></icon-svg></a>
					</span>
				</div>
				<!--设备列表-->
				<el-table border height=500 :key='tableKey' :data='deviceDatas' fit @cell-mouse-enter="showHandle" @cell-mouse-leave="hiddenHandle" v-loading="loading" :element-loading-text="$t('button.loading')" element-loading-background="rgba(255, 255, 255, 1)">
					<el-table-column align="center" :label="$t('index.Number')" fixed="left" width="80px" type='index'> </el-table-column>
					<el-table-column align="center" :label="$t('trade.DeviceID')" width="150px" prop="termId"> 
					</el-table-column>
					<el-table-column align="center" :label="$t('inputBox.merchant')" prop="merName" class-name="title_name" width="180px">
					</el-table-column>
					<el-table-column align="center" :label="$t('inputBox.shop')" width="180px" prop="shopName">
					</el-table-column>
					<el-table-column align="center" :label="$t('inputBox.deviceType')" width="160px" prop="termType" :formatter="judgeType">
					</el-table-column>
					<el-table-column align="center" :label="$t('inputBox.deploymentDate')" prop="modTime" width="230">
					</el-table-column>
					<el-table-column align="center" :label="$t('inputBox.status')" prop="state" width="150" :formatter="judge">
					</el-table-column>
					<el-table-column fixed="right" class-name="animate_td handle-hidden-3">
					    <template slot-scope="scope">
							<a class="svg-link-class" :title="$t('inputBox.change')" v-if="scope.row.termType == '1' && userPhone !== '13501189583' && userPhone !== '15018955912' && userPhone !== '15219441946' " @click="handleDeviceModify(scope.row.termId,scope.row.shopName,scope.row.merId,scope.row.merName)">
								<svg aria-hidden="true" class="svg-icon svg-action-icon"><use xlink:href="#icon-bianji"></use></svg>
							</a>
							<a class="svg-link-class" :title="$t('button.Enabled1')" v-if="scope.row.state !== 1 && scope.row.state !== 3 && userPhone !== '13501189583' && userPhone !== '15018955912' && userPhone !== '15219441946' " @click="enable(scope.row.termId,scope.row.shopName,scope.row.termType)">
								<svg aria-hidden="true" class="svg-icon svg-action-icon"><use xlink:href="#icon-qiyong"></use></svg>
							</a>
							<a class="svg-link-class" :title="$t('button.Suspended2')" v-if="(scope.row.state == 1 || scope.row.state == 3) && userPhone !== '13501189583' && userPhone !== '15018955912' && userPhone !== '15219441946' " @click="disable(scope.row.termId,scope.row.shopName,scope.row.termType)">
								<svg aria-hidden="true" class="svg-icon svg-action-icon"><use xlink:href="#icon-stop"></use></svg>
							</a>
				
							<a class="svg-link-class" :title="$t('inputBox.cancelBinding')" v-if="scope.row.termType == '1' && userPhone !== '13501189583' && userPhone !== '15018955912' && userPhone !== '15219441946' " @click="cancelBind(scope.row.termId,scope.row.shopName)">
								<svg aria-hidden="true" class="svg-icon svg-action-icon"><use xlink:href="#icon-shanchu"></use></svg>
							</a>
							<a class="svg-link-class" :title="$t('inputBox.QRcode')" v-if="scope.row.termType == '0' && (scope.row.state == '3' || scope.row.state == '1' ) " @click="showQrcode(scope.row.termId,scope.row.logo)">
								<svg aria-hidden="true" class="svg-icon svg-action-icon"><use xlink:href="#icon-erweima"></use></svg>
							</a>
						</template>
					</el-table-column>
				</el-table>
			</div>
		</div>

		<div class="pagination-container">
    		<el-pagination @size-change="handleSizeChange" background @current-change="handleCurrentChange" :current-page.sync="searchDeviceData.page" :page-sizes="[15,20,30, 50]" :page-size="searchDeviceData.pageSize" layout="total, sizes, prev, pager, next, jumper" :total="res.total"></el-pagination>
  		</div>
  		
  		<!--设备添加-->
  		<el-dialog :title="$t('device.newDevice')" :visible.sync="dialogDeviceAdd" :lock-scroll=false :show-close=false custom-class="custom-dialog" :before-close="handleClose" :close-on-click-modal=false :modal-append-to-body="true" :append-to-body="true" class="el-dialog-add">
		    <el-form label="right" label-position="top" :inline="true" :rules="addRules" ref="addForm" :model="addDeviceForm">
				<el-form-item :label="$t('device.merchant')">
					<el-select v-model="addDeviceMerData" id="addDeviceMerId" clearable filterable remote :remote-method="remoteMethod_A" :placeholder="$t('placeH.Please')+$t('device.merchant')" @change='addDevice_selectMer()' value-key="merchantId" @clear='addDevice_clearMer()'>
						<el-option v-for="item in queryMerData_A" :key="item.merchantId" :label="item.merchantName" :value="item">
						</el-option>
					</el-select>
				</el-form-item>
				<el-form-item :label="$t('device.shop')">
					<el-select v-model="addDeviceMershopId" id="addDeviceMershopId" clearable filterable :placeholder="$t('placeH.Please')+$t('device.shop')" :disabled='showAddDevice_Shop'>
						<el-option v-for="item in queryAddDevice_ShopData" :key="item.shopId" :label="item.shopName" :value="item.shopId">
						</el-option>
					</el-select>
				</el-form-item>
				<el-form-item :label="$t('device.type')">
					<el-select v-model="addDeviceMerPayType" id="addDeviceMerPayType" clearable :placeholder="$t('placeH.Please')+$t('inputBox.deviceType')">
						<el-option :label="$t('inputBox.QRcode')" value="0"></el-option>
						<el-option :label="$t('inputBox.scanner')" value="1"> </el-option>
					</el-select>
				</el-form-item>
				
				<el-form-item :label="$t('device.deviceID')" v-show="isAddBox" prop="addDeviceMerTermId">
					<el-input v-model="addDeviceForm.addDeviceMerTermId" id="addDeviceMerTermId" :maxlength=16 :placeholder="$t('inputBox.pleaseEnterTheDeviceNumber')"></el-input>
				</el-form-item>
			</el-form>
  			<!-- <span slot="footer" class="dialog-footer">
		    	<el-button type="primary" @click="handleDeviceAdd()">{{$t('button.OK')}}</el-button>
		    	<el-button @click="cancelAdd">{{$t('inputBox.cancel')}}</el-button>
  			</span> -->

  			<div class="el-dialog__footer">
  				<div class="dialog-footer">
  					<button @click="handleDeviceAdd('addForm')" type="button" class="el-button footer-ok el-button--default">
  						<span> {{$t('device.OK')}} </span>
  					</button>
  					<button @click="cancelAdd" type="button" class="el-button footer-cancel footer-cancen-btn el-button--default">
  						<span> {{$t('device.cancel')}} </span>
  					</button>
  				</div>
  			</div>

		</el-dialog>
  		
  		<!--设备修改-->
  		<el-dialog :title="$t('inputBox.deviceModify')" :visible.sync="dialogDeviceModify" custom-class="custom-dialog" :before-close="handleClose" :close-on-click-modal=false class="el-dialog-add" :show-close=false>
		    <el-form label="right" label-position="top" :inline="true">
				<el-form-item :label="$t('device.merchant')">
					<el-select v-model="modifyDevice_merId" id="modifyDevice_merId" clearable filterable remote :remote-method="remoteMethod_M" :placeholder="$t('placeH.Please')+$t('inputBox.merchant')" @change='modifyDevice_selectMer()' value-key="merchantId" @clear='modifyDevice_clearMer()'>
						<el-option v-for="item in queryMerData_M" :key="item.merchantId" :label="item.merchantName" :value="item.merchantId">
						</el-option>
					</el-select>
				</el-form-item>
				<el-form-item :label="$t('inputBox.shop')">
					<el-select v-model="modifyDevice_shopId" id="modifyDevice_shopId" clearable filterable :placeholder="$t('placeH.Please')+$t('inputBox.shop')" :disabled='showModifyDevice_Shop'>
						<el-option v-for="item in queryModifyDevice_ShopData" :key="item.shopId" :label="item.shopName" :value="item.shopId">
						</el-option>
					</el-select>
				</el-form-item>
				<el-form-item :label="$t('device.type')">
					<el-input disabled='disabled' :value="$t('inputBox.scanner')" ></el-input>
				</el-form-item>
				<el-form-item :label="$t('device.deviceID')">
					<el-input disabled='disabled' v-model="modifyDevice_termId"></el-input>
				</el-form-item>
			</el-form>
  			<span slot="footer" class="dialog-footer">
		    	<el-button @click="confirmModify()" class="el-button footer-ok el-button--default">{{$t('button.OK')}}</el-button>
		    	<el-button @click="dialogDeviceModify = false"  type="button" class="el-button footer-cancel footer-cancen-btn el-button--default">{{$t('inputBox.cancel')}}</el-button>
  			</span>
		</el-dialog>

		<!-- 展示固码 -->
		<el-dialog :visible.sync="dialogVisible" custom-class="dialogQrcode" :before-close="closeQrcode">
      		<div id="qrcode">
				
			</div>
			<canvas id="qrcode1">
				<img src="" id="avatar" alt="">		
			</canvas>
    	</el-dialog>
	</div>
</template>

<script>
	import { deviceAll, deviceModify, deviceAdd, devicePage, queryMec, queryShop, add_solidCode, add_box,del_box,toggleDeviceState,queryImg } from 'api/deviceManegement/index';
	import XLSX from "xlsx";
	import XLSX_SAVE from "file-saver";
	import QRCode from 'qrcodejs2'
	import { Base64 } from 'js-base64';
	export default {
		name: 'device',
		data(){
			return {
				companyId:localStorage.getItem('companyId'),
				userPhone:localStorage.getItem('phone'),
				addTermId:'',
				addShopId:'',
				dialogDeviceModify:false,
				dialogDeviceAdd: false,
				//按条件搜索设备所需参数
				searchDeviceData:{
					termId:undefined,
					name:undefined,
					shopName:undefined,
					state:undefined,
					payType:undefined,
					startDate:undefined,
					endDate:undefined,
					page: 1,
				    pageSize: 15,
				},
				//返回数据
				res:[],
				deviceDatas:[],
				//设备添加绑定的数据
				deviceAddData:{
					termId:undefined,
					merchantId:undefined,
				},
			    list: null,
				tableKey: 0,
				queryMerData:[],
				merData:null,
				showQueryShop:true,
				queryShopData:[],
				//新增设备数据
				addDeviceMerData:'',
				addDeviceMerId:'',
				addDeviceMershopId:'',
				addDeviceMerPayType:'',
				queryAddDevice_ShopData:[],
				showAddDevice_Shop:true,
				isAddBox:false,
				//操作按钮	
				tableIndex:null,	
				last_td_arr:[],	
				//修改设备数据
				modifyDevice_termId:'',
				modifyDevice_shopId:'',
				modifyDevice_merId:'',
				queryModifyDevice_ShopData:[],
				showModifyDevice_Shop:false,
				modifyFlag:false,
				addFlag:false,
				searchInfo:'',
				select_shop:false,
				addRules: {
					addDeviceMerTermId: [
					    { required: true, message: ' ', trigger: 'blur' },
            			{ min: 16, max: 16, message: ' ', trigger: 'blur' }
					],
				},
				addDeviceForm:{
					addDeviceMerTermId:'',
				},
				queryMerData_M:[],
				queryMerData_A:[],
				exportSearchData:{},
				dialogVisible:false,
				logoSrc:'',
				qrcodeLogo:'',
				oldPage: null,
      			loading: true,
			}
		},
		watch: {
			'searchDeviceData.name':function(newVal,oldVal){
	
				if ( newVal == '' ) this.showQueryShop = true;
			},
			'addDeviceMerPayType':function(newVal,oldVal){
		
				this.isAddBox = newVal == '1' ? true : false;
			},
			'searchDeviceData.page':function(newVal,oldVal){
			    this.oldPage = oldVal;
			},
		},
		created () {
			this.getDeviceList(this.searchDeviceData);
			this.searchInfo = this.$t('index.Device');
		},
		methods: { 
			// base64 转 blob 转 file
 			BaseToBlobToFile(urlData,callback) {
				const bytes = window.atob(urlData.split(',')[1]);        // 去掉url的头，并转换为byte
				// 处理异常,将ascii码小于0的转换为大于0
				const ab = new ArrayBuffer(bytes.length);
				const ia = new Uint8Array(ab);
				for (let i = 0; i < bytes.length; i++) {
					ia[i] = bytes.charCodeAt(i);
				}
				let blob = new Blob([ab], { type: 'image/png' });

				let a = new FileReader();
				a.onload = function(e) {callback(e.target.result);};
				a.readAsDataURL(blob);
			},
			// 展示固码
			showQrcode(termId,logo){
				let that = this;
				this.dialogVisible = true;
				if( logo == undefined ){
					this.logoSrc = this.companyId == '2' ? 'http://unipock.img-cn-shenzhen.aliyuncs.com/201804/20180411120740832.png' : 'http://unipock.img-cn-shenzhen.aliyuncs.com/201804/20180410180209877.png';
				} else {
					this.logoSrc = logo;
				}

				setTimeout(function(){
					// 生成固码
					let qrcode = new QRCode('qrcode', {
						text: "http://unipock.net/wxjsapi/showpayinfo/solidCodePay/"+ termId +"/unipock.net",
						width: 200,
						height: 200,
						colorDark : "#000000",
						colorLight : "#ffffff",
						correctLevel : QRCode.CorrectLevel.H
					});
					
					var canvas = document.getElementById("qrcode1");
					canvas.width = 240;
					canvas.height = 240;
					var context = canvas.getContext("2d");

					context.rect(0 , 0 , canvas.width , canvas.height);
					context.fillStyle = "#fff";
					context.fill();

					var myImage = new Image();
					myImage.crossOrigin = 'Anonymous';
					
					queryImg({imgUrl:that.logoSrc}).then(res=>{
						that.BaseToBlobToFile(res.value,function(res){
							that.qrcodeLogo = res;
							setTimeout(function(){
								myImage.onload = function(){
									context.drawImage(myImage , 20 , 20 , 200 , 200);

									var myImage2 = new Image();
									myImage2.crossOrigin = 'Anonymous';
									
									myImage2.onload = function(){
										context.drawImage(myImage2 , 100 , 100 , 40 , 40);
										var base64 = canvas.toDataURL("image/png");  //"image/png" 这里注意一下
										var img = document.getElementById('avatar');

										img.setAttribute('src' , base64);
									}
									myImage2.src = that.qrcodeLogo;
								};
								// console.log($("#qrcode img")[0].src);
								myImage.src = $("#qrcode img")[0].src;
							},300)
						})
					})

					

				},200)
			},
			closeQrcode(){
				this.dialogVisible = false;
				setTimeout(function(){
					document.getElementById("qrcode").innerHTML = "";
				},300)
			},
			remoteMethod(query){
				if ( query !== '' ) {
					queryMec({companyId:localStorage.getItem('companyId'),name:query}).then(res=>{
						this.queryMerData = res.value;
					})
				} else {
					this.queryMerData = [];
				}
			},
			remoteMethod_A(query){
				if ( query !== '' ) {
					queryMec({companyId:localStorage.getItem('companyId'),name:query}).then(res=>{
						this.queryMerData_A = res.value;
					})
				} else {
					this.queryMerData_A = [];
				}
			},
			remoteMethod_M(query){
				if ( query !== '' ) {
					queryMec({companyId:localStorage.getItem('companyId'),name:query}).then(res=>{
						this.queryMerData_M = res.value;
					})
				} else {
					this.queryMerData_M = [];
				}
			},
			checkFormData(arr,index){
				
				let falg = index == 0 ? 'addFlag' : 'modifyFlag';
				for(let i = 0;i < arr.length;i++){
				
					if( this[arr[i]] == '' || this[arr[i]] == undefined ){
						$('#'+arr[i]).addClass('invalid');
						$('#'+arr[i]).focus();
						return false;
					}
				}
				this[falg] = true;
			},
			// 启用设备
			enable(termId,shopName,termType){
		
				const deviceType = termType == '0' ? this.$t('inputBox.QRCodeOf') : this.$t('inputBox.scannerOf');  
				const sure = termType == '0' ? this.$t('inputBox.confirmToEnable') : this.$t('inputBox.confirmToEnableS');
				this.$confirm( sure + shopName + deviceType, this.$t('hint.Alert') , {
					confirmButtonText: this.$t('button.OK'),
					closeOnClickModal:false,
					cancelButtonText: this.$t('button.Cancel'),
				}).then(() => {
					toggleDeviceState(termId).then(res=>{
					
						if(res.code==0){
							this.$message({
								type: 'success',
								message: this.$t('hint.OperationSuccess')
							});
						}
						this.handleFilter(1);
					})
				})
			},
			// 停用设备
			disable(termId,shopName,termType){
				
				const deviceType = termType == '0' ? this.$t('inputBox.QRCodeOf') : this.$t('inputBox.scannerOf');
				const sure = termType == '0' ? this.$t('inputBox.confirmToDisable') : this.$t('inputBox.confirmToDisableS');
				this.$confirm( sure + shopName + deviceType, this.$t('hint.Alert') , {
					confirmButtonText: this.$t('button.OK'),
					closeOnClickModal:false,
					cancelButtonText: this.$t('button.Cancel'),
				}).then(() => {
					toggleDeviceState(termId).then(res=>{
						
						if(res.code==0){
							this.$message({
								type: 'success',
								message: this.$t('hint.OperationSuccess')
							});
						}
						this.handleFilter(1);
					})
				}).catch(()=>{})
			},
			// 取消绑定
			cancelBind(termId,shopName){
				this.$confirm(this.$t('inputBox.confirmToUnbind') + shopName + this.$t('inputBox.scannerOf'), this.$t('hint.Alert') , {
					confirmButtonText: this.$t('button.OK'),
					cancelButtonText: this.$t('button.Cancel'),
					closeOnClickModal:false,
				}).then(() => {
					del_box(termId).then(res=>{
						
						if(res.code==0){
							this.$message({
								type: 'success',
								message: this.$t('hint.OperationSuccess')
							});
						}
						this.handleFilter(1);
					})					
				}).catch(()=>{})
			},
			// 鼠标滑入tr
			showHandle(row, column, cell, event){
				// console.log(row);
				for(let i = 0;i<this.deviceDatas.length;i++){
					
					if(this.deviceDatas[i].termId == row.termId){
						this.tableIndex = i;
						const table_row = $(".el-table__fixed-right").find('.el-table__row')[i];
						$(table_row).find('td:last').removeClass('handle-hidden-'+ this.last_td_arr[i] );
						$(".el-table__fixed-right").addClass("fixed-column-" + this.last_td_arr[i] );
						$(".el-table__fixed-right").css("z-index","22");
						var action_div = $(table_row).find('td:last').children("div");
						$(action_div).stop().animate({"right": "0"});
					}
				}
				// 判断项目数目是否导致滚动条出现
				if(this.deviceDatas.length <= 15 ){
					$(".el-table__fixed-right").addClass("right-zero");
				}else{
					$(".el-table__fixed-right").removeClass("right-zero");
				}
			},
			// 鼠标滑出tr
			hiddenHandle(row, column, cell, event){
				const table_row = $(".el-table__fixed-right").find('.el-table__row')[this.tableIndex];
				$(".el-table__fixed-right").css("z-index","0");
				var action_div = $(table_row).find('td:last').children("div");
				$(action_div).stop().animate({"right": "-360px"});
			},
			// 修改店铺选中商户下拉框变化时触发
			modifyDevice_selectMer(){
				this.modifyDevice_shopId = undefined;
				queryShop({merchantId:this.modifyDevice_merId}).then(res=>{
					this.queryModifyDevice_ShopData = res.value;
					this.showModifyDevice_Shop = false;
				})
			},
			//修改设备 清空商户选项
			modifyDevice_clearMer(){
				this.modifyDevice_shopId = '';
				this.showModifyDevice_Shop = true;
			},
			//取消新增
			cancelAdd(){
				this.addDeviceMerData = '';
				this.addDeviceMerId = '';
				this.addDeviceMershopId = '';
				this.addDeviceMerPayType = '';
				this.addDeviceForm.addDeviceMerTermId = '';
				this.dialogDeviceAdd = false;
				this.showAddDevice_Shop = true;
				let arr = ['addDeviceMerId','addDeviceMershopId','addDeviceMerPayType','addDeviceMerTermId'];
				for(let i = 0;i<arr.length;i++){
					$('#'+arr[i]).removeClass('invalid');
				}
				this.$refs['addForm'].resetFields();
			},
			// 新增设备 清空商户选项
			addDevice_clearMer(){
				this.addDeviceMerData = '';
				this.addDeviceMershopId = '';
				this.showAddDevice_Shop = true;
				this.queryMerData_A = [];
			},
			//新增设备选择商户下拉框变化时触发
			addDevice_selectMer(){
				this.addDeviceMershopId = undefined;
				this.addDeviceMerId = this.addDeviceMerData.merchantId;
				if(this.addDeviceMerData != "") {
					queryShop(this.addDeviceMerData).then(res=>{
						this.queryAddDevice_ShopData = res.value;
					})
					this.showAddDevice_Shop = false;
				};
			},
			// 搜索 清空商户选项
			clearMer(){
				this.searchDeviceData.name = '';
				this.searchDeviceData.shopName = '';
				this.queryMerData = [];
				this.showQueryShop = true;
				this.select_shop = false;
			},
			// 搜索 选择商户下拉框变化时触发
			selectMer(){
				this.searchDeviceData.name = this.merData.merchantName;
				this.searchDeviceData.shopName = undefined;
				if(this.merData != "") {
					queryShop(this.merData).then(res=>{
						this.queryShopData = res.value;
					})
					this.showQueryShop = false;
					this.select_shop = true;
				}
				
			},
			//清空筛选条件
			delSelect(){
				this.searchDeviceData.termId='';
				this.searchDeviceData.name='';
				this.searchDeviceData.startDate='';
				this.searchDeviceData.endDate='';
				this.searchDeviceData.shopName='';
				this.searchDeviceData.state='';
				this.searchDeviceData.payType='';
				this.merData = null;
				this.queryMerData = [];
				this.showQueryShop = true;
				this.select_shop = false;
				this.searchInfo =  this.$t('index.Device');
				this.handleFilter(1);
			},
			// 格式化设备类型
			judgeType(row){
				let type = row.termType;//0固码 1盒子
			
				return type = type == '0' ? this.$t('inputBox.QRcode') : this.$t('inputBox.scanner');
			},
			//格式化
			judge(row){
				let state = row.state;
			
				return state = state == 1 || state == 3 ? this.$t('inputBox.enabled') : this.$t('inputBox.disabled');
			},
			//商户详情的确定按钮绑定的方法
			handleClose(done) {
		        done();
		    },
		    //设备修改的方法
			handleDeviceModify(termId,shopId,merId,merName){
				this.modifyDevice_termId = termId;
				queryShop({merchantId:Number(merId)}).then(res=>{
					this.queryModifyDevice_ShopData = res.value;
					this.showModifyDevice_Shop = false;
				})
				this.remoteMethod_M(merName);
				this.modifyDevice_merId = Number(merId);
				this.modifyDevice_shopId = shopId;
				this.dialogDeviceModify = true;
			},
			//设备修改 确认
			confirmModify(){
				let arr = ['modifyDevice_merId','modifyDevice_shopId'];
				this.checkFormData(arr,1);

				if(this.modifyFlag){
					let deviceModifyData = {
						termId:this.modifyDevice_termId,
						shopId:this.modifyDevice_shopId,
						merchantId:this.modifyDevice_merId,
					}
					deviceModify(deviceModifyData).then(res=>{
						// console.log('设备修改确认按钮后台返回的信息')
						// console.log(res)
						
						if(res.success == true){
							this.getDeviceList(this.searchDeviceData);
							this.dialogDeviceModify = false;
							this.$notify({
								title: this.$t('inputBox.success'),
								message: this.$t('inputBox.modifySuccess'),
								type: 'success',
								duration: 2000
							});
						}else{
							this.$notify({
								title: this.$t('inputBox.fail'),
								message: this.$t('hint.FailToEdit'),
								type: 'error',
								duration: 2000
							});
						}
					})
				}
			},
			//设备添加的方法
			handleDeviceAdd(){
				// 如果设备类型为派派小盒
				
				if( this.addDeviceMerPayType  == '1'){
					// 如果设备编号为空
					if(this.addDeviceForm.addDeviceMerTermId == "") {
						$('#addDeviceMerTermId').addClass('invalid').focus();
						return false;
					}
					// 验证表单中的设备编号格式
					this.$refs['addForm'].validate((valid) => {
						// 如果验证不通过
						if(!valid){
							return false;
						}else {
							this.postDeviceAdd();
						}
					})
				} else {
                    this.postDeviceAdd();
                }
			},
			// 提交请求设备添加的方法
			postDeviceAdd() {
				let arr = ['addDeviceMerId','addDeviceMershopId','addDeviceMerPayType']; // 存放需要验证的字段
				// 验证提交的数据 0 addFlag 1 modifyFlag
				this.checkFormData(arr,0);

				// 如果验证数据通过
				if(this.addFlag){
		
					const func = this.addDeviceMerPayType == '1' ? add_box : add_solidCode;
					let deviceAddData = {
						merchantId:this.addDeviceMerId,
						shopId:this.addDeviceMershopId
					}
			
					if( this.addDeviceMerPayType == '1' ){
						deviceAddData.termId = this.addDeviceForm.addDeviceMerTermId;
					} 
					func(deviceAddData).then(res=>{
						this.cancelAdd();
						this.addFlag = false;
					
						if(res.code == 0){
							this.addDeviceMerData = '';
							this.addDeviceMerId = '';
							this.addDeviceMershopId = '';
							this.addDeviceMerPayType = '';
							this.addDeviceForm.addDeviceMerTermId = '';
							this.getDeviceList(this.searchDeviceData);
							this.dialogDeviceAdd = false;
							this.$notify({
								title: this.$t('inputBox.success'),
								message: this.$t('inputBox.addSuccess'),
								type: 'success',
								duration: 2000
							});
						
						} else if(res.code== -1){
							this.$notify({
								title: this.$t('inputBox.fail'),
								message: this.$t('device.deviceNAE'),
								type: 'error',
								duration: 2000
							});
						} else{
							this.$notify({
								title: this.$t('inputBox.fail'),
								message: this.$t('inputBox.addFail'),
								type: 'error',
								duration: 2000
							});
						}
					})
				}
			},
			//封装了设备管理的方法
			getDeviceList(value,str){
				const _that = this;
				this.last_td_arr = [];
				value.companyId = this.companyId;
				deviceAll(value).then(res => {
					// console.log('设备管理后台返回的数据')
					// console.log(res)
					this.res = res.value;
					this.deviceDatas = res.value.list;

					// 如果是分页触发，循环去除选中样式，对点击后的项数添加选中样式
					if( str == 'CurrentChange' ){
					  let obj = $('.el-pager .number');
					  for( let i = 0; i < obj.length; i++){
					      if($(obj[i]).html() == this.searchDeviceData.page) {
					        $(obj[i]).addClass('active');
					      } else {
					        $(obj[i]).removeClass('active');
					      }
					  }
					}

					setTimeout(function () { 
						const td_last_child = $(".el-table__body-wrapper tr td:last-child");
						for(let i=0;i<td_last_child.length;i++){
							$(td_last_child[i]).removeClass('handle-hidden-3');
						}
						const td_fixed_last_child = $(".el-table__fixed-right tr td:last-child");
						for(let i=0;i<td_fixed_last_child.length;i++){
							// console.log($(td_fixed_last_child[i]).find('.svg-link-class').length);
							_that.last_td_arr.push($(td_fixed_last_child[i]).find('.svg-link-class').length);
							
							if( $(td_fixed_last_child[i]).find('.svg-link-class').length == 1 ){
								$(td_fixed_last_child[i]).removeClass('handle-hidden-3').removeClass('handle-hidden-2').addClass('handle-hidden-1');
							
							} else if( $(td_fixed_last_child[i]).find('.svg-link-class').length == 2 ){
								$(td_fixed_last_child[i]).removeClass('handle-hidden-3').removeClass('handle-hidden-1').addClass('handle-hidden-2');
							
							} else if( $(td_fixed_last_child[i]).find('.svg-link-class').length == 3 ){
								$(td_fixed_last_child[i]).removeClass('handle-hidden-1').removeClass('handle-hidden-2').addClass('handle-hidden-3');
							} 
						}
						const title_name_arr = $(".el-table__body-wrapper .title_name .cell");
						for(let j = 0;j<title_name_arr.length;j++){
							$(title_name_arr[j]).attr('title',$(title_name_arr[j]).html());
							// if(_that.getStrL($(title_name_arr[j]).html()) > 25 ){
							// }
						}
						
						// 隐藏载入提示层
						_that.loading = false;
						
					},500)
				}).catch(error=>{
					console.log(error);
				})
			},
			// 判断字符串长度的方法
			getStrL(str){
				let l = str.length; 
				let blen = 0; 
				for(let i=0; i<l; i++) { 
					if ((str.charCodeAt(i) & 0xff00) != 0) { 
						blen ++; 
					} 
					blen ++; 
				}
				return blen;
			},
			//点击搜索 设备管理
		    handleFilter(sign,str) {

		    	// 显示载入提示层
		    	this.loading = true;
			
				if(sign == 0) this.searchInfo =  this.$t('index.searchResults');
		    	//查询设备的参数
		    	this.exportSearchData = {};
				$.extend(this.exportSearchData, this.searchDeviceData);
		    	this.formatObj(this.exportSearchData);
				this.getDeviceList(this.exportSearchData,str);

				if( str == 'CurrentChange' ){
				  // 获取所有分页项数，循环去除选中样式，对点击前的项数添加选中样式
				  let obj = $('.el-pager .number');
				  for( let i = 0; i < obj.length; i++){
				      if($(obj[i]).html() == this.oldPage) {
				        console.log(this.oldPage);
				        $(obj[i]).addClass('active');
				      } else {
				        $(obj[i]).removeClass('active');
				      }
				  }
				}
		    },
		    //pageSize 改变时会触发
		    handleSizeChange(val) {
		        this.searchDeviceData.pageSize = val;
		        this.handleFilter(1);
		    },
		    //currentPage 改变时会触发
		    handleCurrentChange(val) {
		        this.searchDeviceData.page = val;
		        this.handleFilter(1,'CurrentChange');
			},
			//导出表格
			export2Excel() {
				require.ensure([], () => {
					let listQuery = {};
					$.extend(listQuery, this.exportSearchData);
                    listQuery.pageSize = this.res.total;
                    listQuery.companyId = this.companyId;
					deviceAll(listQuery).then(res => {
						const { export_json_to_excel } = require("../../vendor/Export2Excel");
						const tHeader = [
							this.$t('trade.DeviceID'),
							this.$t('inputBox.merchant'),
							this.$t('inputBox.shop'),
							this.$t('inputBox.deviceType'),
							this.$t('inputBox.deploymentDate'),
							this.$t('inputBox.status'),
						]; //对应表格输出的title
						const tHeader_Au = [
							this.$t('trade.DeviceID'),
							this.$t('inputBox.merchant'),
							this.$t('inputBox.shop'),
							this.$t('inputBox.deviceType'),
							this.$t('inputBox.deploymentDate'),
							this.$t('inputBox.status'),
						]; //对应表格输出的title
						const filterVal = [
							"termId",
							"merName",
							"shopName",
							"termType",
							"modTime",
							"state",
						]; // 对应表格输出的数据
						const filterVal_Au = [
							"termId",
							"merName",
							"shopName",
							"termType",
							"modTime",
							"state",
						]; // 对应表格输出的数据
						const list = res.value.list;
						for (let i = 0; i < list.length; i++) {
							
							list[i].state = list[i].state == 1 || list[i].state == 3 ? this.$t('inputBox.enabled') : this.$t('inputBox.disabled');
					
							list[i].termType = list[i].termType == '0' ? this.$t('inputBox.QRcode') : this.$t('inputBox.scanner');
							
						}
						const data = this.formatJson((this.companyId == 1 ? filterVal : filterVal_Au), list);
						export_json_to_excel((this.companyId == 1 ? tHeader : tHeader_Au), data, this.$t('trade.Device')); //对应下载文件的名字
					});
				});
			},
			formatJson(filterVal, jsonData) {
				return jsonData.map(v => filterVal.map(j => v[j]));
			},
			formatObj(obj) {
				let arr = Object.keys(obj);
				for (let i = 0; i < arr.length; i++) {
					
					if (obj[arr[i]] == "") {
					obj[arr[i]] = null;
					}
				}
			}
		}
	}

</script>


<style>
</style>

